#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

"""
@author: JoeyZhou
@Tool: PyCharm
@Date: 2020/2/18 11:42 AM
@desc: 
"""

import smtplib
import time
import os
import logging
from os import path
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


class SendEmail:

    def __init__(self):
        pass

    # 发送邮件
    def send_mail(self, file_new):
        # 收件人邮箱的服务器
        SMTPserver = "smtp.exmail.qq.com"
        # 发送人的邮箱和密码
        sender = "yi.zhou@aihuishou.com"
        password = "JZQe9twS9DbV5SfJ"
        # 收件人的邮箱
        destination = "397034688@qq.com"
        # destination = 'kenzop@126.com,397034688@qq.com'
        destinations = destination.split(',')
        now = time.strftime('%Y-%m-%d')
        with open(file_new, "rb") as f:
            mail_body = f.read()

        # 邮件的标题Subject、发信人From、收件人To
        msg = MIMEMultipart()
        body = MIMEText(mail_body, _subtype="HTML", _charset="UTF-8")
        msg["Subject"] = "自动化测试报告" + now
        msg["From"] = sender
        msg["To"] = ",".join(destinations)
        msg.attach(body)

        # 附件
        # part = MIMEApplication(open(file_new, 'wb').read())
        # part.add_header('Content-Disposition', 'attachment', filename=msg["Subject"] + '.html')
        # msg.attach(part)

        # 连接邮箱
        mailserver = smtplib.SMTP(SMTPserver, 25)
        mailserver.login(sender, password)
        mailserver.sendmail(sender, destinations, msg.as_string())
        mailserver.quit()
        logging.info('===邮件已发送===')


if __name__ == '__main__':

    parent_path = path.dirname(path.dirname(__file__))  # 获得当前目录的父级目录
    reports_path = parent_path + "/reports/email_reports/"
    a = os.listdir(reports_path)
    datanames = sorted(a, reverse=True)
    list = []
    for dataname in datanames:
        if os.path.splitext(dataname)[1] == '.html':  # 目录下包含.html的文件
            list.append(dataname)
    print(list)
    print(list[0])
    reports_path = reports_path + list[0]
    print(reports_path)

    se = SendEmail()
    se.send_mail(reports_path)
